<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 外呼任务控制器
 *
 * @author Alen
 * @since 1.0 2014-6-26 by sutroon
 */
class TaskController extends AppbaseController {

    public function get_task_list_json() {
        $this->ajaxReturn(AddonD('Task')->get_task_list(array('taskStrategyID' => I('tsid'))));
    }

    /**
     * 检测用户余额
     * @return bool
     * @since 1.0 2014-11-24 by sutroon
     */
    public function check_user_blance_tip($siteID = 0) {
        if ($siteID && sofn_check_user_blance_state($siteID)) {
            echo '1';
        } else {
            if ($siteID) {
                M('tcti_task')->where('siteID=' . $siteID)->setField('state', '0');
            }
            echo '0';
        }
    }

    function set_task_state($id = 0, $tsid = 0, $state = 0) {
        if (!$id) {
            $this->ajaxMsg(false, '编号无效!');
        }
        if ($state == '') {
            $this->ajaxMsg(false, '参数有误!');
        }
        $M = M('tcti_task');
        $where['id'] = $id;
        $list = $M->where($where)->getField('id,state,source,siteID');
        if (!$list) {
            $this->ajaxMsg(false, '任务不存在!');
        }
        $source = $list[$id]['source'];
        if ($source == '') {
            $this->ajaxMsg(false, '任务来源有误!');
        }
        $stat = $list[$id]['state'];
        if ($stat == $state) {
            $this->ajaxMsg(false, '重复操作!');
        }
        if ($state == 1) {
            $siteID = $list[$id]['siteID'];
            if (!sofn_check_user_blance_state($siteID)) {
                $this->ajaxMsg(false, '您的可用余额不足，请充值!');
            }
        }
        $count1 = $M->where('taskStrategyID=' . $tsid . ' and state=1')->count();
        $count0 = $M->where('taskStrategyID=' . $tsid . ' and state=0')->count();
        $count = $M->where('taskStrategyID=' . $tsid)->count();
        $result = $M->where($where)->setField('state', $state);
        if ($result === false) {
            $this->ajaxMsg(false, '操作失败!' . $M->getDbError());
        } else {
            // 如果状态是启动且该策略下没有任何启动的任务则发socket
            // echo "<div style='font-size:12px;'>[state=$state, count1=$count1, $count0=$count0, count=$count]</div>";
            $msg = $this->send_task_socket($id, $tsid, $state);
            if ('ok' == $msg) {
                $this->ajaxMsg(true, '操作成功!');
            } else {
                $this->ajaxMsg(false, '命令执行失败:' . var_export($msg, true));
            }
        }
    }

    function send_task_socket($id, $tsid, $state) {
        return sofn_socket_send("$tsid,$id,$state");
    }

    function set_task_state_batch($tsid = 0, $state = '') {
        if (!$tsid) {
            $this->ajaxMsg(false, '编号无效!');
        }
        if ($state == '') {
            $this->ajaxMsg(false, '参数有误!');
        }
        $where = "taskStrategyID=$tsid";
        $M = M('tcti_task');
        $count = $M->where($where . ' and unCallCount>0')->count();
        if ($count < 1) {
            $this->ajaxMsg(false, '没有需要操作的任务!');
        }
        if ($state == 1) {
            $siteID = $M->where($where)->getField('siteID');
            if (!sofn_check_user_blance_state($siteID)) {
                $this->ajaxMsg(false, '您的可用余额不足，请充值!');
            }
        }
        $count1 = $M->where($where . ' and state=1 and unCallCount>0')->count();
        $count0 = $M->where($where . ' and state=0 and unCallCount>0')->count();
        $result = $M->where($where . ' and unCallCount>0')->setField('state', $state);
        if ($result === false) {
            $this->ajaxMsg(false, '操作失败!');
        } else {
            // 如果状态是启动且该策略下没有任何启动的任务则发socket
            $msg = $this->send_task_socket(0, $tsid, $state);
            if ('ok' == $msg) {
                $this->ajaxMsg(true, '操作成功!');
            } else {
                $this->ajaxMsg(false, '命令执行失败 ' . $msg);
            }
        }
    }

    public function task_delete($id = '') {
        if (!$id) {
            $this->ajaxMsg(false, '编号无效!');
        }
        $msg = AddonD('Task')->item_remove($id);
        $this->ajaxMsg($msg['status'] ? true : false, $msg['info']);
    }

    public function add_number($tsid = 0) {
        if (!$tsid) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $this->assign('tsid', $tsid);
        $this->display();
    }

    public function add_number_save() {
        $tsid = I('taskStrategyID');
        $phoneNo = I('phoneNumber');
        $params = new \Org\Su\Params();
        if (!$phoneNo) {
            $params->addError('电话号码未填写');
        }
        $params->addParam('strategy_id', 'number', '任务策略未选择', false, $tsid);
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }

        $list = M('tcti_task_strategy')->where('id=' . $tsid)->getField('siteID,trunkName');
        if (!$list) {
            $this->ajaxMsg(false, '策略不存在!');
        }
        $siteID = key($list);
        $trunkName = current($list);
        if (!$siteID) {
            $this->ajaxMsg(false, '策略归属有误!');
        }
        if ($tsid) {
            if (!D('Task')->check_max_task_num($siteID, $tsid, 1)) {
                $this->ajaxMsg(false, '该任务策略中所有任务号码数量已超过您的最大任务数,请在该任务策略中删除部分任务后继续操作!');
            }
        }
        $phoneNo = preg_replace('/[^\d]/i', '', $phoneNo);
        $taskName = I('name');
        if (!$taskName) {
            $taskName = $phoneNo;
        }
        $data = array('name' => $taskName, 'taskStrategyID' => $tsid, 'trunkName' => $trunkName, 'source' => 'add', 'telsCount' => 1, 'unCallCount' => 1, 'remark' => '', 'siteID' => $siteID);
        $M = M('tcti_task');
        $task_id = $M->add($data);
        if ($task_id === false) {
            $this->ajaxMsg(false, '执行失败!');
        } else {
            $data = array('taskID' => $task_id, 'trunkName' => $trunkName, 'taskStrategyID' => $tsid, 'phoneNumber' => $phoneNo, 'customerName' => '', 'source' => 'add', 'siteID' => $siteID,);
            $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $tsid;
            M($table)->add($data);
            AddonD('Task')->duplicate_task_to_redis($task_id, $tsid);
            $this->ajaxMsg(true, '执行成功!');
        }
    }

    public function generate_number($tsid = 0) {
        if (!$tsid) {
            $this->ajaxMsg(false, '编号有误!');
        }
        $this->assign('tsid', $tsid);
        $this->display();
    }

    public function generate_number_save() {
        $tsid = I('taskStrategyID');
        $notype = I('noType');
        $chkTaskSplit = I('chkTaskSplit');
        $params = new \Org\Su\Params();
        $params->addParam('taskStrategyID', 'number', '任务策略未选择');
        if ($notype == 'mob') {
            $params->addParam('province', 'require', '省份未选择');
            $params->addParam('city', 'require', '城市未选择');
            $params->addParam('operator', 'number', '运营商未选择');
            $params->addParam('areaName', 'require', '归属地号段未选择');
            $params->addParam('name', 'require', '名称无效');
        } else {
            $params->addData('name', I('startNo'));
        }
        $params->addParam('startNo', 'number', '号码范围未填写');
        $params->addParam('endNo', 'number', '结束号码未填写');
        $params->addParam('rule', 'require', '生成规则无效');
        if ($chkTaskSplit) {
            $params->addParam('telsCount', 'number', '号码数量无效');
            $params->addParam('taskCount', 'number', '任务数量无效');
        }
        if (I('chkLastNo')) {
            $params->addParam('lastNo', 'number', '尾数号无效');
            $params->addParam('maxNum', 'number', '最大数量无效');
            $params->addData('telsCount', 0);
        }
        $params->addData('skipDuplicate');
        $params->addData('prefix');
        $params->addData('remark');
        if ($params->hasError()) {
             $this->ajaxMsg(false, $params->getError());
        }
        $params->removeParam('taskCount');
        $data = M('tcti_task_strategy')->field('siteID, trunkName')->find($tsid);
        $siteID = $data['siteID'];
        $trunkName = $data['trunkName'];
        if (!$siteID) {
             $this->ajaxMsg(false, '策略归属有误!');
        }

        $endNo = I('endNo');
        $startNo = I('startNo');
        if ($notype == 'mob' && strlen($startNo) != 11) {
            $params->addError('号码范围必需11位!');
        }
        if ($endNo < 1 || $endNo > 10000) {
            $params->addError('结束号码只能在1-9999之间!');
        }
        if ($params->hasError()) {
             $this->ajaxMsg(false, $params->getError());
        }

        if ($tsid) {
            if (!D('Task')->check_max_task_num($siteID, $tsid, $endNo)) {
                 $this->ajaxMsg(false, '该任务策略中所有任务号码数量已超过您的最大任务数,请在该任务策略中删除部分任务后继续操作!');
            }
        }
        $params->addData('createdTime', date('Y-m-d H:i:s'));
        $params->addData('siteID', $siteID);
        $params->addData('source', 'generate');

        $M = M('tcti_task');
        if ($M->where("startNo='$startNo' and taskStrategyID=$tsid")->count() > 0) {
            //2015-5-25 已在前台控制,此处限制取消  $this->ajaxMsg(false, '该任务策略中已添加过此号段!');
        }

        if ($chkTaskSplit) {
            $taskCount = I('taskCount');
            $data = $params->getParams();
            for ($i = 0; $i < $taskCount; $i++) {
                unset($data['id']);
                $id = $M->add($data);
                if (false === $id) {
                    die($M->getDbError());
                     $this->ajaxMsg(false, '添加任务失败!');
                } else {
                    $data['id'] = $id;
                    M('tcti_task_history')->add($data);
                    $this->generate_number_generate($id, $trunkName, $data, $i);
                }
            }
                $this->ajaxMsg(true, '添加任务成功!');
            //$this->result(true, '添加任务成功!', AddonU('TaskStrategy/index', 'id=' . $tsid));
        } else {
            $data = $params->getParams();
            unset($data['id']);
            $id = $M->add($data);
            if (false === $id) {
                 $this->ajaxMsg(false, '添加任务失败!');
            } else {
                M('tcti_task_history')->add($data);
                $this->generate_number_generate($id, $trunkName, $data);
                $this->ajaxMsg(true, '添加任务成功!');
            }
        }
    }

    public function generate_number_save2() {
        $tsid = I('taskStrategyID');
        $notype = I('noType');
        $chkTaskSplit = I('chkTaskSplit');
        $params = new \Org\Su\Params();
        $params->addParam('taskStrategyID', 'number', '任务策略未选择');
        if ($notype == 'mob') {
            $params->addParam('province', 'require', '省份未选择');
            $params->addParam('city', 'require', '城市未选择');
            $params->addParam('operator', 'number', '运营商未选择');
            $params->addParam('areaName', 'require', '归属地号段未选择');
            $params->addParam('name', 'require', '名称无效');
        } else {
            $params->addData('name', I('startNo'));
        }
        $params->addParam('startNo', 'number', '号码范围未填写');
        $params->addParam('endNo', 'number', '结束号码未填写');
        $params->addParam('rule', 'require', '生成规则无效');
        if ($chkTaskSplit) {
            $params->addParam('telsCount', 'number', '号码数量无效');
            $params->addParam('taskCount', 'number', '任务数量无效');
        }
        if (I('chkLastNo')) {
            $params->addParam('lastNo', 'number', '尾数号无效');
            $params->addParam('maxNum', 'number', '最大数量无效');
            $params->addData('telsCount', 0);
        }
        $params->addData('skipDuplicate');
        $params->addData('prefix');
        $params->addData('remark');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $params->removeParam('taskCount');
        $data = M('tcti_task_strategy')->field('siteID, trunkName')->find($tsid);
        $siteID = $data['siteID'];
        $trunkName = $data['trunkName'];
        if (!$siteID) {
            $this->ajaxMsg(false, '策略归属有误!');
        }

        $endNo = I('endNo');
        $startNo = I('startNo');
        if ($notype == 'mob' && strlen($startNo) != 11) {
            $params->addError('号码范围必需11位!');
        }
        if ($endNo < 1 || $endNo > 10000) {
            $params->addError('结束号码只能在1-9999之间!');
        }
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }

        if ($tsid) {
            if (!D('Task')->check_max_task_num($siteID, $tsid, $endNo)) {
                $this->ajaxMsg(false, '该任务策略中所有任务号码数量已超过您的最大任务数,请在该任务策略中删除部分任务后继续操作!');
            }
        }
        $params->addData('siteID', $siteID);
        $params->addData('source', 'generate');

        $M = M('tcti_task');
        /* 2015-5-25 已在前台控制,此处限制取消
          if ($M->where("startNo='$startNo' and taskStrategyID=$tsid")->count() > 0) {
          $this->ajaxMsg(false,'该任务策略中已添加过此号段!');
          } */

        if ($chkTaskSplit) {
            $taskCount = I('taskCount');
            $data = $params->getParams();
            $data['trunkName'] = $trunkName;
            $ids = '';
            for ($i = 0; $i < $taskCount; $i++) {
                unset($data['id']);
                $id = $M->add($data);
                if (false === $id) {
                    die($M->getDbError());
                    $this->ajaxMsg(false, '添加任务失败!');
                } else {
                    $data['id'] = $id;
                    M('tcti_task_history')->add($data);
                    if ($i > 0) {
                        $id.=',';
                    }
                    $ids.=$id;
                    $this->generate_number_generate($id, $trunkName, $data, $i);
                }
            }
            //$this->success('任务添加成功,正在生成号码...', AddonU('Task/generate_number_step2', 'id=' . $ids));
            $this->ajaxMsg(true, '添加任务成功!');
        } else {
            $data = $params->getParams();
            $data['trunkName'] = $trunkName;
            unset($data['id']);
            $id = $M->add($data);
            if (false === $id) {
                $this->ajaxMsg(false, '添加任务失败!');
            } else {
                M('tcti_task_history')->add($data);
                $this->generate_number_generate($id, $trunkName, $data);
                $this->ajaxMsg(true, '添加任务成功!');
            }
        }
    }

    // 2015-2-2 by sutroon
    public function generate_numberq($tsid = '') {
        if (!$tsid) {
            $this->ajaxMsg(false, '编号有误!');
        }
        $this->assign('tsid', $tsid);
        $this->display();
    }

    // 快速生成号码 2015-2-2 by sutroon
    public function generate_numberq_save() {
        $tsid = I('taskStrategyID');
        $rule = I('rule');
        $startNos = I('startNo'); // 号码范围
        $endNos = I('endNo'); // 结束号码
        $lastNos = I('lastNo'); // 最后号码
        $params = new \Org\Su\Params();
        $params->addParam('taskStrategyID', 'number', '任务策略未选择');
        if (!array_filter($startNos) || !array_filter($endNos)) {
            $params->addError('号码范围或结束号码未填写');
        }
        $params->addParam('rule', 'require', '生成规则无效');
        if ($params->hasError()) {
             $this->ajaxMsg(false, $params->getError());
        }

        $i = 0;
        foreach ($startNos as $startNo) {
            $endNo = $endNos[$i];
            if (!$startNo || !$endNo) {
                continue;
            }
            if ($endNo < 1 || $endNo > 10000) {
                $params->addError("结束号码[$endNo]只能在1-9999之间!");
            }
            $i++;
        }
        if ($params->hasError()) {
             $this->ajaxMsg(false, $params->getError());
        }

        $data = M('tcti_task_strategy')->field('siteID, trunkName')->find($tsid);
        $siteID = $data['siteID'];
        $trunkName = $data['trunkName'];
        if (!$siteID) {
             $this->ajaxMsg(false, '策略归属有误!');
        }
        if ($tsid) {
            if (!D('Task')->check_max_task_num($siteID, $tsid, $endNo)) {
                 $this->ajaxMsg(false, '该任务策略中所有任务号码数量已超过您的最大任务数,请在该任务策略中删除部分任务后继续操作!');
            }
        }

        $M = M('tcti_task');
        $n = 0;
        foreach ($startNos as $startNo) {
            if (!$startNo || !$endNos[$n]) {
                continue;
            }
            $data['name'] = $startNo . '-' . $lastNos[$n];
            $data['taskStrategyID'] = $tsid;
            $data['source'] = 'generate';
            $data['startNo'] = $startNo; // 号码范围
            $data['endNo'] = $endNos[$n]; // 结束号码
            $data['rule'] = $rule;
            $data['telsCount'] = $endNos[$n]; // 号码数量
            $data['siteID'] = $siteID;
            $data['createdTime'] = date('Y-m-d H:i:s');
            unset($data['id']);
            /* echo '<br />单个:'.$i.'<br />';
              var_export($data); */
            $id = $M->add($data);
            if (false === $id) {
                die($M->getDbError());
            } else {
                $data['id'] = $id;
                M('tcti_task_history')->add($data);
                $this->generate_number_generate($id, $trunkName, $data, 0, false);
            }
            $n++;
        }
        $this->ajaxMsg(true, '添加任务成功!');
    }

    function generate_number_generate($task_id, $trunkName, $data, $n = 0, $updateTaskName = true) {
        if(!$task_id){
            return;
        }
        ignore_user_abort();
        set_time_limit(800);
        $tsid = $data['taskStrategyID'];
        $endNo = $data['endNo'];
        $startNo = $data['startNo'];
        $lastNo = $data['lastNo'];
        $maxNum = $data['maxNum'];
        $prefix = $data['prefix'];
        $skipDuplicate = $data['skipDuplicate'];
        $siteID = $data['siteID'];
        $rule = $data['rule'];
        $telsCount = $data['telsCount']; // 是否拆分任务

        $curNum = floor($endNo / $lastNo);
        if ($curNum < 1) {
            $curNum = 1;
        }
        $endNo = $endNo - 1;
        $endNoLen = strlen($endNo);
        $diffbit = strlen($maxNum) - strlen($curNum);
        if ($diffbit > 0) {
            $padchar = substr($endNo, $endNoLen - 1);
            $endNo = str_pad($endNo, $endNoLen + $diffbit, $padchar);
        }
        $endNoLen = strlen($endNo);
        $startNo = substr($startNo, 0, -$endNoLen);
        $istart = 0;
        $arrVals = array();
        if ($telsCount) {
            $istart = $telsCount * $n;
            $endNo = $istart + $telsCount;
        }
        $M = M('tcti_task');
        for ($i = $istart; $i <= $endNo; $i++) {
            $num = $prefix . $startNo . str_pad($i, $endNoLen, '0', STR_PAD_LEFT);
            if ($telsCount > 0 && $i == $istart) {
                $name = $data['name'];
                if (false !== ($pos = strrpos($name, ';'))) {
                    $name = substr($name, 0, $pos + 2) . $num;
                } else {
                    $name = $num;
                }
                if ($updateTaskName) {
                    $M->where("id=$task_id")->setField('name', $name);
                    $M->table('tcti_task_history')->where("id=$task_id")->setField('name', $name);
                }
            }
            if ($lastNo != '') {
                if (sofn_end_with($num, $lastNo)) {
                    $arrVals[] = sprintf('%s,%d,%d,%s,generate,%d', $trunkName, $tsid, $task_id, $num, $siteID);
                }
                continue;
            }
            $arrVals[] = sprintf('%s,%d,%d,%s,generate,%d', $trunkName, $tsid, $task_id, $num, $siteID);
        }
        $count = count($arrVals);
        if ($count == 0) {
             $this->ajaxMsg(false, '生成号码失败,没有生成满足条件的号码');
            return;
        }
        if ($rule == 'random') {
            shuffle($arrVals);
        }
        // 创建临时表
        // $table_tmp = sofn_get_sharding_field('DB_IMPORT_TEMP') . 'tcall_number_temp_' . $siteID;
        // $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $tsid;
        $table_tmp = 'tcall_number_temp_' . $siteID;
        $table = 'tcti_call_number' . $tsid;
        $user_key = C('USER.USER_KEY');
        $filename = RUNTIME_PATH . '/Sqls/';
        if (!is_dir($filename)) {
            mkdir($filename);
        }
        //$filename = 'F:\\\\PDC\\\\ProjectEnv\\\\xcall150505\\\\Application\\\\Runtime\\\\Sqls\\\\' . strtolower($user_key) . '_callnumber_' . $task_id . '.sql';
        $filename = '/var/www/html/xcall/Application/Runtime/Sqls/' . strtolower($user_key) . '_callnumber_' . $task_id . '.sql';
        $file = fopen($filename, 'w');
        foreach ($arrVals as $sql) {
            fwrite($file, $sql . PHP_EOL);
        }
        fclose($file);
        $sql = "load data infile '$filename' into table $table_tmp" . ' character set utf8 FIELDS TERMINATED BY "," ENCLOSED BY \'"\' ESCAPED BY "\\\" LINES TERMINATED BY "\n" STARTING BY "" (trunkName, taskStrategyID, taskID, phoneNumber, source, siteID)';
        //echo $sql;
        M()->execute('SET UNIQUE_CHECKS=0');
        M()->execute($sql);
        sleep(3);
        if ($skipDuplicate) {
            $dup = M()->execute("delete $table_tmp from $table_tmp INNER JOIN $table on $table_tmp.phoneNumber=$table.phoneNumber where $table_tmp.taskID=$task_id;");
            if (false !== $dup) {
                $count = $count - $dup;
            }
        }
        M()->execute('insert into ' . $table . ' (taskID, trunkName, taskStrategyID, phoneNumber, source, siteID) select taskID, trunkName, taskStrategyID, phoneNumber, source, siteID from ' . $table_tmp . ' where taskID=' . $task_id);
        M($table_tmp)->where('taskID=' . $task_id)->delete();
        if (M($table_tmp)->count() < 1) {
            M()->execute('truncate table ' . $table_tmp);
        }
        M()->execute('SET UNIQUE_CHECKS=1');
        $M->where('id=' . $task_id)->setField(array('telsCount' => $count, 'unCallCount' => $count));
        AddonD('Task')->duplicate_task_to_redis($task_id, $tsid);
    }

    function generate_number_generate2($task_id, $n = 0, $updateTaskName = true) {
        ignore_user_abort();
        set_time_limit(800);
        $M = M('tcti_task');
        $data = $M->field('`name`, taskStrategyID, trunkName, endNo, startNo, lastNo, maxNum, prefix, skipDuplicate, source, startNo, endNo, rule, telsCount,siteID')->find($task_id);
        $tsid = $data['taskStrategyID'];
        $trunkName = $data['trunkName'];
        $endNo = $data['endNo'];
        $startNo = $data['startNo'];
        $lastNo = $data['lastNo'];
        $maxNum = $data['maxNum'];
        $prefix = $data['prefix'];
        $skipDuplicate = $data['skipDuplicate'];
        $siteID = $data['siteID'];
        $rule = $data['rule'];
        $telsCount = $data['telsCount']; // 是否拆分任务
        F('task_' . $task_id, var_export($data, true));

        $curNum = floor($endNo / $lastNo);
        if ($curNum < 1) {
            //$curNum = 1; 2015-8-20 修正
            $curNum = $endNo;
        }
        $endNo = $endNo - 1;
        $endNoLen = strlen($endNo);
        $diffbit = strlen($maxNum) - strlen($curNum);
        if ($diffbit > 0) {
            $padchar = substr($endNo, $endNoLen - 1);
            $endNo = str_pad($endNo, $endNoLen + $diffbit, $padchar);
        }
        $endNoLen = strlen($endNo);
        $startNo = substr($startNo, 0, -$endNoLen);
        $istart = 0;
        $arrVals = array();
        if ($telsCount) {
            $istart = $telsCount * $n;
            $endNo = $istart + $telsCount;
        }
        for ($i = $istart; $i <= $endNo; $i++) {
            $num = $prefix . $startNo . str_pad($i, $endNoLen, '0', STR_PAD_LEFT);
            if ($telsCount > 0 && $i == $istart) {
                $name = $data['name'];
                if (false !== ($pos = strrpos($name, ';'))) {
                    $name = substr($name, 0, $pos + 2) . $num;
                } else {
                    $name = $num;
                }
                if ($updateTaskName) {
                    $M->where("id=$task_id")->setField('name', $name);
                    M('tcti_task_history')->where("taskID=$task_id")->setField('name', $name);
                }
            }
            if ($lastNo != '') {
                if (sofn_end_with($num, $lastNo)) {
                    $arrVals[] = sprintf('%s,%d,%d,%s,generate,%d', $trunkName, $tsid, $task_id, $num, $siteID);
                }
                continue;
            }
            $arrVals[] = sprintf('%s,%d,%d,%s,generate,%d', $trunkName, $tsid, $task_id, $num, $siteID);
        }
        $count = count($arrVals);
        if ($count == 0) {
            $this->ajaxMsg(false, '生成号码失败,没有生成满足条件的号码');
            return;
        }
        if ($rule == 'random') {
            shuffle($arrVals);
        }
        // 创建临时表
        // $table_tmp = sofn_get_sharding_field('DB_IMPORT_TEMP') . 'tcall_number_temp_' . $siteID;
        // $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $tsid;
        $table_tmp = 'tcall_number_temp_' . $siteID;
        $table = 'tcti_call_number' . $tsid;
        $user_key = C('USER.USER_KEY');
        $filename = RUNTIME_PATH . '/Sqls/';
        if (!is_dir($filename)) {
            mkdir($filename);
        }
        //$filename = 'F:\\\\PDC\\\\ProjectEnv\\\\xcall150505\\\\Application\\\\Runtime\\\\Sqls\\\\' . strtolower($user_key) . '_callnumber_' . $task_id . '.sql';
        $filename = '/var/www/html/xcall/Application/Runtime/Sqls/' . strtolower($user_key) . '_callnumber_' . $task_id . '.sql';
        $file = fopen($filename, 'w');
        foreach ($arrVals as $sql) {
            fwrite($file, $sql . PHP_EOL);
        }
        fclose($file);
        $sql = "load data infile '$filename' into table $table_tmp" . ' character set utf8 FIELDS TERMINATED BY "," ENCLOSED BY \'"\' ESCAPED BY "\\\" LINES TERMINATED BY "\n" STARTING BY "" (trunkName, taskStrategyID, taskID, phoneNumber, source, siteID)';
        //echo $sql;
        M()->execute('SET UNIQUE_CHECKS=0');
        M()->execute($sql);
        sleep(3);
        if ($skipDuplicate) {
            $dup = M()->execute("delete $table_tmp from $table_tmp INNER JOIN $table on $table_tmp.phoneNumber=$table.phoneNumber where $table_tmp.taskID=$task_id;");
            if (false !== $dup) {
                $count = $count - $dup;
            }
        }
        M()->execute('insert into ' . $table . ' (taskID, trunkName, taskStrategyID, phoneNumber, source, siteID) select taskID, trunkName, taskStrategyID, phoneNumber, source, siteID from ' . $table_tmp . ' where taskID=' . $task_id);
        M($table_tmp)->where('taskID=' . $task_id)->delete();
        if (M($table_tmp)->count() < 1) {
            M()->execute('truncate table ' . $table_tmp);
        }
        M()->execute('SET UNIQUE_CHECKS=1');
        $M->where('id=' . $task_id)->setField(array('telsCount' => $count, 'unCallCount' => $count));
        AddonD('Task')->duplicate_task_to_redis($task_id, $tsid);
    }

    public function import_number() {
        $tsid = I('tsid');
        if (!$tsid) {
            $this->ajaxMsg(false, '编号有误!');
        }
        $this->assign('tsid', $tsid);
        $this->display();
    }

    public function import_number_save() {
        ignore_user_abort();
        set_time_limit(800);
        $msg = AddonD('Task')->import_upload();
        if (!$msg['status']) {
            $this->ajaxMsg(false, $msg['info']);
        }
        $id = $msg['info'];
        $msg = AddonD('Task')->import_to_sql($id);
        if ($msg['status']) {
            $this->ajaxMsg(true);
        } else {
            $this->ajaxMsg(false, $msg['info']);
        }
    }

    public function task_recycling($id = 0) {
        if (!$id) {
            $this->ajaxMsg(false, '编号有误!');
        }
        $data = M('tcti_task')->find($id);
        if ($data) {
            if (strpos($data['name'], '-')) {
                $data['name'] = substr($data['name'], 0, strpos($data['name'], '-'));
            }
            $data['name'] = $data['name'] . '-' . date('Hi');
            $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $data['taskStrategyID'];
            $list = M($table)->field('phoneNumber,state')->where('taskID=' . $id)->limit(10)->select();
            $this->assign('data', $data);
            $this->assign('list', $list);
        }
        $this->display();
    }

    public function task_recycling_save() {
        $id = I('id');
        $tsid = I('tsid');
        $state = I('state');
        $name = I('name');
        $err = false;
        if (!$name) {
            $err[] = '任务名称未填写!';
        }
        if (!$state) {
            $err[] = '号码状态未选择!';
        }
        if (!$id) {
            $err[] = '编号无效!';
        }
        if ($err) {
            $this->ajaxMsg(implode("\n", $err));
        }
        if (in_array(-1, $state)) {
            $strstate = '';
        } else {
            $strstate = sprintf(' and state in (%s)', implode(',', $state));
        }
        $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $tsid;
        $field = ('TTF' == C('USER.USER_KEY')) ? "phoneNumber as '电话号码',customerName as '客户姓名',sex as '性别',idNo as '身份证号', card_no as '卡号', address as '联系地址'" : "customerName as '姓名', phoneNumber as '号码',detailMsg as '其他备注'";
        $list = M($table)->where('taskID=' . $id . $strstate)->field($field)->select();
        $count = count($list);
        if (!$list) {
            $this->ajaxMsg(false, '任务里面没有符合查询的号码!');
        }
        if (!IS_AJAX) {
            sofn_excel_export($list);
        } else {
            $M = M('tcti_task');
            $data = $M->find($id);
            unset($data['id']);
            $data['createdTime'] = date('Y-m-d H:i:s');
            $arr = array('callCount', 'callRate', 'callSuccessCount', 'callFailCount', 'noAnswerCount', 'arriveSeatCount', 'arriveSeatRate', 'connRate', 'state');
            foreach ($arr as $k) {
                $data[$k] = 0;
            }
            $data['telsCount'] = $count;
            $data['unCallCount'] = $count;
            $data['createdTime'] = date('Y-m-d H:i:s');
            $data['name'] = $name;
            $newtid = $M->add($data);
            if ($newtid === false) {
                $this->ajaxMsg(false, '操作失败![ADD FAIL]');
            }
            $result = $M->execute("insert into $table (taskID, trunkName, taskStrategyID, phoneNumber, customerName, sex, idNo, card_no, address, info1, info2, detailMsg, source, state, siteID) select $newtid, trunkName, taskStrategyID, phoneNumber, customerName, sex, idNo, card_no, address, info1, info2, detailMsg, source, 0, siteID from $table where taskID=$id $strstate;");
            if ($result !== false) {
                // 2014-11-12 $result = $M->execute("insert into tcti_call_plan (taskID, trunkName, taskStrategyID, source, sourceID, phoneNumber) select taskID, trunkName, taskStrategyID, source, id, phoneNumber from tcti_call_number$tsid where taskID=$newtid;");
            }
            if ($result === false) {
                $this->ajaxMsg(false, '操作失败!' . $M->getDbError());
            } else {
                $this->ajaxMsg(true, '操作成功,<br />请刷新列表!');
            }
        }
    }

    public function check_history() {
        $startNo = I('startNo');
        $tsid = I('tsid');
        $siteID = M('tcti_task_strategy')->where("id=$tsid")->getField('siteID');
        if (!$siteID) {
            $this->ajaxRetrn(array('count' => 1, 'msg' => '请求参数有误，请刷新页面!'));
            return;
        }
        $createdTime = M('tcti_task_history')->where("startNo='$startNo' and siteID=$siteID")->getField('createdTime');
        $msg = $createdTime ? array('count' => 1, 'msg' => sprintf('号段[%s]在[%s]已经生成过了，是否继续生成?', $startNo, $createdTime)) : array('count' => 0, 'msg' => '');
        $this->ajaxReturn($msg);
    }

    public function task_history_of_generate() {
        $this->display();
    }

    public function get_taskhistory_list_json() {
        $where['source'] = 'generate';
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $list = AddonD('TaskHistory')->get_taskhistory_list($where);
        $this->ajaxReturn($list);
    }

    public function task_history_of_generate_batch_delete($id = '') {
        if (!$id) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $result = M('tcti_task_history')->delete($id);
        $this->ajaxMsg($result, '删除{%}');
    }

    function get_data($province = null) {
        $arr['北京'] = array('北京市');
        $arr['上海'] = array('上海市');
        $arr['天津'] = array('天津市');
        $arr['重庆'] = array('重庆市');
        $arr['河北'] = array('石家庄', '邯郸', '邢台', '保定', '张家口', '承德', '廊坊', '唐山', '秦皇岛', '沧州', '衡水');
        $arr['山西'] = array('太原', '大同', '阳泉', '长治', '晋城', '朔州', '吕梁', '忻州', '晋中', '临汾', '运城');
        $arr['内蒙古'] = array('呼和浩特', '包头', '乌海', '赤峰', '呼伦贝尔盟', '阿拉善盟', '哲里木盟', '兴安盟', '乌兰察布盟', '锡林郭勒盟', '巴彦淖尔盟', '伊克昭盟');
        $arr['新疆'] = array('博乐', '喀什', '和田', '乌鲁木齐', '库尔勒', '阿勒泰', '石河子', '阿克苏', '昌吉', '伊犁', '克拉玛依', '奎屯', '吐鲁番', '克州', '塔城', '哈密', '阿图什', '博尔塔拉', '巴州', '克孜勒苏', '托里', '皮山', '富蕴', '精河', '乌苏', '库车', '巴楚', '伊宁');
        $arr['辽宁'] = array('沈阳', '大连', '鞍山', '抚顺', '本溪', '丹东', '锦州', '营口', '阜新', '辽阳', '盘锦', '铁岭', '朝阳', '葫芦岛');
        $arr['吉林'] = array('长春', '吉林', '四平', '辽源', '通化', '白山', '松原', '白城', '延边');
        $arr['黑龙江'] = array('哈尔滨', '齐齐哈尔', '牡丹江', '佳木斯', '大庆', '绥化', '鹤岗', '鸡西', '黑河', '双鸭山', '伊春', '七台河', '大兴安岭');
        $arr['江苏'] = array('南京', '镇江', '苏州', '南通', '扬州', '盐城', '徐州', '连云港', '常州', '无锡', '宿迁', '泰州', '淮安');
        $arr['浙江'] = array('杭州', '宁波', '温州', '嘉兴', '湖州', '绍兴', '金华', '衢州', '舟山', '台州', '丽水');
        $arr['安徽'] = array('合肥', '芜湖', '蚌埠', '马鞍山', '淮北', '铜陵', '安庆', '黄山', '滁州', '宿州', '池州', '淮南', '巢湖', '阜阳', '六安', '宣城', '亳州');
        $arr['福建'] = array('福州', '厦门', '莆田', '三明', '泉州', '漳州', '南平', '龙岩', '宁德');
        $arr['江西'] = array('南昌市', '景德镇', '九江', '鹰潭', '萍乡', '新馀', '赣州', '吉安', '宜春', '抚州', '上饶');
        $arr['山东'] = array('济南', '青岛', '淄博', '枣庄', '东营', '烟台', '潍坊', '济宁', '泰安', '威海', '日照', '莱芜', '临沂', '德州', '聊城', '滨州', '菏泽');
        $arr['河南'] = array('郑州', '开封', '洛阳', '平顶山', '安阳', '鹤壁', '新乡', '焦作', '濮阳', '许昌', '漯河', '三门峡', '南阳', '商丘', '信阳', '周口', '驻马店', '济源');
        $arr['湖北'] = array('武汉', '宜昌', '荆州', '襄樊', '黄石', '荆门', '黄冈', '十堰', '恩施', '潜江', '天门', '仙桃', '随州', '咸宁', '孝感', '鄂州');
        $arr['湖南'] = array('长沙', '常德', '株洲', '湘潭', '衡阳', '岳阳', '邵阳', '益阳', '娄底', '怀化', '郴州', '永州', '湘西', '张家界');
        $arr['广东'] = array('广州', '深圳', '珠海', '汕头', '东莞', '中山', '佛山', '韶关', '江门', '湛江', '茂名', '肇庆', '惠州', '梅州', '汕尾', '河源', '阳江', '清远', '潮州', '揭阳', '云浮');
        $arr['广西'] = array('南宁', '柳州', '桂林', '梧州', '北海', '防城港', '钦州', '贵港', '贺州', '百色', '河池');
        $arr['海南'] = array('海口', '三亚');
        $arr['四川'] = array('成都', '绵阳', '德阳', '自贡', '攀枝花', '广元', '内江', '乐山', '南充', '宜宾', '广安', '达川', '雅安', '眉山', '甘孜', '凉山', '泸州');
        $arr['贵州'] = array('贵阳', '六盘水', '遵义', '安顺', '铜仁', '黔西南', '毕节', '黔东南', '黔南');
        $arr['云南'] = array('昆明', '大理', '曲靖', '玉溪', '昭通', '楚雄', '红河', '文山', '思茅', '西双版纳', '保山', '德宏', '丽江', '怒江', '迪庆', '临沧');
        $arr['西藏'] = array('拉萨', '日喀则', '山南', '林芝', '昌都', '阿里', '那曲');
        $arr['陕西'] = array('西安', '宝鸡', '咸阳', '铜川', '渭南', '延安', '榆林', '汉中', '安康', '商洛');
        $arr['甘肃'] = array('兰州', '嘉峪关', '金昌', '白银', '天水', '酒泉', '张掖', '武威', '定西', '陇南', '平凉', '庆阳', '临夏', '甘南');
        $arr['宁夏'] = array('银川', '石嘴山', '吴忠', '固原');
        $arr['青海'] = array('西宁', '海东', '海南州', '海北', '黄南', '玉树', '果洛', '海西', '格尔木', '同仁', '门源');
        return $province && array_key_exists($province, $arr) ? $arr[$province] : $arr;
    }

    public function get_province_json() {
        //$this->ajaxReturn(array());
        //exit;
        $data = array_keys($this->get_data());
        $out = array();
        foreach ($data as $item) {
            $out[] = array('id' => $item, 'text' => $item);
        }
        $this->ajaxReturn($out);
    }

    public function get_city_json() {
        $province = I('province');
        if (!$province) {
            return;
        }
        $data = $this->get_data($province);
        $out = array();
        foreach ($data as $item) {
            $out[] = array('id' => $item, 'text' => $item);
        }
        $this->ajaxReturn($out);
    }

    public function get_startNo_list() {
        $areaname = I('areaname');
        $phoneGear = I('phonegear');
        $isp = I('isp');
        if (!$areaname) {
            $this->ajaxReturn(array());
        }
        if (!$phoneGear) {
            $phoneGear = "手机";
        }
        $sql = "areaName like '%$areaname%'";
        $fields = "numberPart as id, concat(replace(areaName,'(*)',''),' >> ',numberPart) as text";
        switch ($phoneGear) {
            case "手机":
                $sql .= "  and length(numberPart)>5";
                break;
            default:
                $sql .= " and length(numberPart)<5";
                $fields = "numberPart as id, concat(cast(phoneLength as varchar(6)), '位 >> 固话位数：',numberPart ) as name";
                break;
        }
// isp 移动、联通、电信
        $yidong = "134,135,136,137,138,139,147,150,151,152,157,158,159,182,183,184,187,188";
        $liantong = "130,131,132,145,155,156,185,186";
        $dianxin = "133,153,180,181,189";
        switch ($isp) {
            case "移动":
                $sql .= sprintf(" and left(numberPart,3) in ('%s') ", implode("','", explode(',', $yidong)));
                break;
            case "联通":
                $sql .= sprintf(" and left(numberPart,3) in ('%s') ", implode("','", explode(',', $liantong)));
                break;
            case "电信":
                $sql .= sprintf(" and left(numberPart,3) in ('%s') ", implode("','", explode(',', $dianxin)));
                break;
        }
        $sql = "select $fields from db_xcall_service.tcti_number_start where $sql order by numberPart";
        $list = M()->query($sql);
        if ($list === false) {
            die('');
        }
        $this->ajaxReturn($list);
    }

    public function get_task_json() {
        if ($this->isSuperAdmin) {
            if (I('siteID')) {
                $where['siteID'] = I('siteID');
            }
        } else {
            $where['siteID'] = $this->loginData['siteID'];
        }
        if (I('tsid')) {
            $where['taskStrategyID'] = I('tsid');
        }
        $data = M('tcti_task')->where($where)->field('id, name as text')->select();
        $this->ajaxReturn($data);
    }

}
